<template>
  <div class="login">
    <div class="login_main">
      <div class="login_main_header">
        <img src="@/assets/favicon.png" alt="">
      </div>
      <div class="login_content">
        <el-form ref="ruleFormRef" :model="ruleForm" label-width="120px" class="demo-ruleForm" :size="formSize">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password" type="password" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="Login()">
              登录
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">清空</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { getUser } from '@/api/http';
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  username: 'admin',
  password: '111111',
})
const router = useRouter()
const Login = () => {
  if (ruleForm.username === '') {
    ElMessage.error('用户名不能为空')
  } else if (ruleForm.password === '') {
    ElMessage.error('密码不能为空')
  } else {
    getUser().then(res => {
      const userInfo = res.data.find((item: any) => {
        return item.username === ruleForm.username
      })
      if (userInfo) {
        if (userInfo.password === ruleForm.password) {
          ElMessage({
            message: '登录成功！正在跳转页面',
            type: 'success',
          })
          setTimeout(() => {
            sessionStorage.setItem('token', userInfo.token)
            router.push('/')
          }, 1000);
        } else {
          ElMessage.error('密码输入错误')
        }
      } else {
        ElMessage.error('用户名不存在,请联系管理员！')
      }
    })
  }
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__content {
  justify-content: center;
}

::v-deep .el-form-item {
  margin-bottom: 30px;
}

.login {
  width: 100%;
  height: 100vh;
  background: #202741;
  display: flex;
  align-items: center;

  .login_main {
    width: 30%;
    height: 370px;
    background: #b6c0db;
    margin: 0 auto;
    border-radius: 20px;
    box-shadow: 0px 0px 10px 0px #bdc0dd;

    .login_main_header {
      height: 100px;
      margin-top: 20px;

      img {
        width: 15%;
        border-radius: 50%;
        display: block;
        margin: 0 auto;
      }
    }

    .login_content {
      margin-top: 30px;
      width: 80%;

    }
  }
}
</style>